package com.example.projectmanagement.repository.study;

import com.example.projectmanagement.model.study.Answer;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.model.study.Question;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;

@Repository
public interface AnswerRepository extends JpaRepository<Answer, Long> {
    List<Answer> findByQuestion(Question question);
    Page<Answer> findByQuestion(Question question, Pageable pageable);
    Page<Answer> findByUser(User user, Pageable pageable);
    List<Answer> findByQuestionAndIsAcceptedTrue(Question question);
    List<Answer> findByParentAnswer(Answer parentAnswer);
    @Query("SELECT a FROM Answer a WHERE a.parentAnswer.id IN :parentAnswerIds")
    List<Answer> findByParentAnswerIdIn(@Param("parentAnswerIds") List<Long> parentAnswerIds);
    
    @Query("SELECT a FROM Answer a LEFT JOIN FETCH a.user LEFT JOIN FETCH a.question WHERE a.question = :question")
    Page<Answer> findByQuestionWithUserAndQuestion(@Param("question") Question question, Pageable pageable);
    
    @Query("SELECT COUNT(a) FROM Answer a WHERE a.user.id = :userId")
    Integer countAnswersByUserId(@Param("userId") Long userId);
    
    @Query("SELECT COUNT(a) FROM Answer a WHERE a.user.id = :userId AND a.isAccepted = true")
    Integer countAcceptedAnswersByUserId(@Param("userId") Long userId);
    
    @Query("SELECT a FROM Answer a LEFT JOIN FETCH a.user LEFT JOIN FETCH a.question WHERE a.id = :id")
    Optional<Answer> findByIdWithUserAndQuestion(@Param("id") Long id);
    
    @Query("SELECT a FROM Answer a LEFT JOIN FETCH a.user LEFT JOIN FETCH a.question LEFT JOIN FETCH a.parentAnswer WHERE a.question = :question")
    Page<Answer> findByQuestionWithUserAndQuestionAndParentAnswer(@Param("question") Question question, Pageable pageable);
    
    @Query("SELECT a FROM Answer a LEFT JOIN FETCH a.user LEFT JOIN FETCH a.question LEFT JOIN FETCH a.parentAnswer WHERE a.user = :user")
    Page<Answer> findByUserWithUserAndQuestionAndParentAnswer(@Param("user") User user, Pageable pageable);
}